<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class pro_event extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		$this->load->model('pro_event_model', 'Event');
		$this->secure_session();
	}
	
	function index(){
		$data['title'] = "Data Event";

		$query = $this->db->query("SELECT no_event FROM (SELECT * FROM pro_event ORDER BY no_event DESC) WHERE rownum <= 1");
		$getquery = $query->row_array();

		if($getquery)
			$MaxID = $getquery['no_event'];
		else
			$MaxID = "EV0000000";

		$NextID = (int) substr($MaxID,2,7);

		$NextID++;
		
		$data['no_event'] = "EV" . sprintf("%07s",$NextID);

		viewByTemplate('pro_event/index', $data, 'grid');
	}

	function create(){
		$data['title'] = "Data Event";

		$query = $this->db->query("SELECT no_event FROM (SELECT * FROM pro_event ORDER BY no_event DESC) WHERE rownum <= 1");
		$getquery = $query->row_array();

		if($getquery)
			$MaxID = $getquery['no_event'];
		else
			$MaxID = "EV0000000";

		$NextID = (int) substr($MaxID,2,7);

		$NextID++;
		
		$data['no_event'] = "EV" . sprintf("%07s",$NextID);

		$query = $this->db->query("SELECT id_event FROM (SELECT * FROM pro_event ORDER BY id_event DESC) WHERE rownum <=1");
				 				if ($query->row_array()) {
				 					$getquery = $query->row_array();
				 					$rowcount = $getquery['id_event'];
				 					$autonum = $rowcount + 1;
				 				} else {
								$autonum = 1;
							}
		$data['id_event_auto'] = $autonum;

		viewByTemplate('pro_event/form', $data, 'grid');
	}

	function edit($id){
		$data['title'] = "Data Event";

		$query = $this->db->query("SELECT
					id_event,	
					no_event,
					no_surat,
					nama_event,
					jam_kegiatan,
					keterangan,
					jenis_event,
					izin_kepolisian,
					to_char(to_date(tanggal_mulai_kegiatan, 'dd-MON-yy'), 'DD/MM/YYYY') as tanggal_mulai_kegiatan,
					to_char(to_date(tanggal_selesai_kegiatan, 'dd-MON-yy'), 'DD/MM/YYYY') as tanggal_selesai_kegiatan
					FROM	pro_event
					WHERE	no_event = '$id'");

		$getquery = $query->row_array();
		
		$data['data'] = $getquery;

		viewByTemplate('pro_event/form', $data, 'grid');
	}
	 
	function getdata()
	{
		$this->secure_session();
		echo $this->Event->GetJSON();
	}

	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty = $this->MessageTemplate("ER001");
		$tpl_duplicate = $this->MessageTemplate("ER002");
		// Validation aa
		
		/*if (post("no_event") == '') {
			$error->Add("no_event", "No Event", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT 1 FROM pro_event WHERE no_event = '".@ereg_replace("[^a-zA-Z0-9_-]", "",@strtoupper(@trim(post("no_event"))))."'")) > 0) {
			$error->Add("no_event", "No Event", $tpl_duplicate);
		}else if (post("nama_event") == '') {
			$error->Add("nama_event", "Nama Event", $tpl_empty);
		}/*else if (post("tanggal_event") == '') {
			$error->Add("tanggal_event", "Tanggal Event", $tpl_empty);
		}else if (post("jenis_event") == '') {
			$error->Add("jenis_event", "Jenis Event", $tpl_empty);
		}*/

		return $error;
	}
	
	function ajax_post($data_input="")
	{
		// echo str_replace("index.php/", "", base_url());

		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";

		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{

				$tgl_old = str_replace(" ", "", $this->input->post('tanggal_mulai_kegiatan'));

				$tahun_new = substr($tgl_old, 6, 4);
				$bulan_new = substr($tgl_old, 3, 2);
				$hari_new   = substr($tgl_old, 0, 2);

				$tgl_new = $tahun_new."-".$bulan_new."-".$hari_new;

				$tgl_old1 = str_replace(" ", "", $this->input->post('tanggal_selesai_kegiatan'));

				$tahun_new1 = substr($tgl_old1, 6, 4);
				$bulan_new1 = substr($tgl_old1, 3, 2);
				$hari_new1   = substr($tgl_old1, 0, 2);

				$tgl_new1 = $tahun_new1."-".$bulan_new1."-".$hari_new1;

				// Fill Post Data
				$data = array(
					'id_event' => $this->input->post('id_event'),
					'no_event' => $this->input->post('no_event'),
					'nama_event' => $this->input->post('nama_kegiatan'),
					'tanggal_mulai_kegiatan' => $tgl_new,
					'tanggal_selesai_kegiatan' => $tgl_new1,
					'jam_kegiatan' => $this->input->post('jam_kegiatan'),
					'jenis_event' => $this->input->post('jenis_event'),
					'keterangan' => $this->input->post('keterangan'),
					'izin_kepolisian' => $this->input->post('izin_kepolisian'),
					'no_surat' => $this->input->post('no_surat')
					);

				if (post("mode") == "create")
				{
					$this->Event->Add($data);

					$ls_response = "Data Tersimpan";

				}
				else if (post("mode") == "edit")
				{
					
					$this->Event->Update($data, array('no_event'	=> $data['no_event']));

					$ls_response = "Data Tersimpan [edited]";
				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
					
			echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
														'fields'	=> $error->GetDictionary(),
														'msg'		=> $ls_response,
														'genid'		=> $ls_genid,
														'form_sender'=> post("form_sender"))
									));
	}

	function ajax_delete()
	{
		$ls_result	= "";
		$no_event	= get('no_event');
		
		if ($no_event != "")
		{
			// Delete Single
			$arr_rule	= array('no_event' => $no_event);
			$ls_result = $this->Event->DeleteSingle($arr_rule);

			
		}
		else
		{
			
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('no_event' => $row['no_event']);
				$ls_result .= $this->Event->DeleteSingle($arr_rule);
			}
		}
		
		echo $ls_result;
	}

	function uploads_data()
	{
		$this->db->where("no_event",$this->input->post('no_event_img'));
		$cek_data = $this->db->get("pro_event");
		if ($cek_data->num_rows() > 0) {

		$ThumbSquareSize 		= 200; //Thumbnail will be 200x200
		$BigImageMaxSize 		= 500; //Image Maximum height or width
		$ThumbPrefix			= "thumb_"; //Normal thumb Prefix
		$DestinationDirectory	= APPPATH.'/file/event/'; //Upload Directory ends with / (slash)
		$Quality 				= 90;

		//ini_set('memory_limit', '-1'); // maximum memory!
// var_dump($_FILES);
		foreach($_FILES as $file)
		{
		// some information about image we need later.
		$ImageName 		= $file['name'];
		$ImageSize 		= $file['size'];
		$TempSrc	 	= $file['tmp_name'];
		$ImageType	 	= $file['type'];


		if (is_array($ImageName)) 
		{
			$c = count($ImageName);
			
			echo  '<ul>';
			
			for ($i=0; $i < $c; $i++)
			{
				$processImage			= true;	
				$RandomNumber			= rand(0, 9999999999);  // We need same random name for both files.
				
				if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
				{
					echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
				}
				else
				{
					//Validate file + create image from uploaded file.
					switch(strtolower($ImageType[$i]))
					{
						case 'image/png':
							$CreatedImage = imagecreatefrompng($TempSrc[$i]);
							break;
						case 'image/gif':
							$CreatedImage = imagecreatefromgif($TempSrc[$i]);
							break;
						case 'image/jpeg':
						case 'image/pjpeg':
							$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
							break;
						default:
							$processImage = false; //image format is not supported!
					}
					//get Image Size
					list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);

					//Get file extension from Image name, this will be re-added after random name
					$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
					$ImageExt = str_replace('.','',$ImageExt);
			
					//Construct a new image name (with random number added) for our new image.
					$NewImageName = $RandomNumber.'.'.$ImageExt;

					//Set the Destination Image path with Random Name
					$thumb_DestRandImageName 	= $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
					$DestRandImageName 			= $DestinationDirectory.$NewImageName; //Name for Big Image

					//Resize image to our Specified Size by calling resizeImage function.
					$this->resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]);
					
					// echo "<img scr='".str_replace("/index.php", "", base_url())."uploads/".$NewImageName."'>";
					$last_id_foto = $this->get_last_id_foto();

					$arr_foto_event = array(
						'id_foto_event' => $last_id_foto, 
						'kode_event' => $this->input->post('no_event_img'),
						'nama_file' => $NewImageName
					);

					$this->db->insert('pro_event_foto',$arr_foto_event);
				}
				
			}
			echo '</ul>';
			}
		} 			
		} 

		/*$cek_foto = $this->db->query("select * from pro_event_foto where kode_event = '".$this->input->post('no_event_img')."'");

		if ($cek_foto->result_array() > 0) {
			foreach ($cek_foto->result_array() as $r_event_foto) {
				echo "<tr>
					<td><img src='".str_replace("/index.php", "", base_url())."uploads/".$r_event_foto['nama_file']."' width='370px' height='230px'></td>
					</tr>
				";
			}
		}*/

		// echo "<script>loadPage('/pro_event/edit/".$this->input->post('no_event_img')."');</script>";
	}

	function get_last_id_foto()
	{
		$query = $this->db->query("SELECT id_foto_event FROM (SELECT * FROM pro_event_foto ORDER BY id_foto_event DESC) WHERE rownum <= 1");
		$getquery = $query->row_array();

		if($getquery)
			$MaxID = $getquery['id_foto_event'] + 1;
		else
			$MaxID = 1;

		return $MaxID;
	}
	
// This function will proportionally resize image 
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
	//Check Image size is not 0
	if($CurWidth <= 0 || $CurHeight <= 0) 
	{
		return false;
	}
	
	//Construct a proportional size of new image
	$ImageScale      	= min($MaxSize/$CurWidth, $MaxSize/$CurHeight); 
	$NewWidth  			= ceil($ImageScale*$CurWidth);
	$NewHeight 			= ceil($ImageScale*$CurHeight);
	
	if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
	{
		$NewWidth = $CurWidth;
		$NewHeight = $CurHeight;
	}
	$NewCanves 	= imagecreatetruecolor($NewWidth, $NewHeight);
	// Resize Image
	if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
	{
		switch(strtolower($ImageType))
		{
			case 'image/png':
				imagepng($NewCanves,$DestFolder);
				break;
			case 'image/gif':
				imagegif($NewCanves,$DestFolder);
				break;			
			case 'image/jpeg':
			case 'image/pjpeg':
				imagejpeg($NewCanves,$DestFolder,$Quality);
				break;
			default:
				return false;
		}
	if(is_resource($NewCanves)) { 
      imagedestroy($NewCanves); 
    } 
	return true;
	}

}

}
?>
